using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Spread.Common.Features.Sample;
using FarPoint.Win.Chart;
using FarPoint.Win.Spread.Data;
using FarPoint.Win.Spread.Model;

namespace Spread.Charts
{
    public partial class AdvancedCharts : BaseSampleControl
    {
        Dictionary<string, Dictionary<string, Type>> _chartTypes = new Dictionary<string, Dictionary<string, Type>>
        {            
            {"Radar", new Dictionary<string, Type>
            {
                {"Point", typeof(RadarPointSeries) },
                {"Line", typeof(RadarLineSeries) },
                {"Area", typeof(RadarAreaSeries) },
            }
            },
            {"Polar", new Dictionary<string, Type>
            {
                {"Point", typeof(PolarPointSeries) },
                {"Line", typeof(PolarLineSeries) },
                {"Area", typeof(PolarAreaSeries) }
            }
            },
            {"Frequency", new Dictionary<string, Type>
            {
                {"Histogram", typeof(HistogramSeries) },
                {"Pareto", typeof(ParetoSeries) },
            }
            },
            {"Funnel", new Dictionary<string, Type>
            {
                {"Funnel", typeof(FunnelSeries) },
            }
            },
            {"Box and Whisker", new Dictionary<string, Type>
            {
                {"Box and Whisker", typeof(BoxWhiskerSeries) },
                {"Clustered", typeof(ClusteredBoxWhiskerSeries) },
            }
            },
            {"Waterfall", new Dictionary<string, Type>
            {
                {"Waterfall", typeof(WaterfallSeries) },
            }
            },
            {"Hierarchy", new Dictionary<string, Type>
            {
                {"Sunburst", typeof(SunburstSeries) },
                {"TreeMap", typeof(TreemapSeries) },
            }
            },
        };
        SpreadDataBindingAdapter _dataAdapter;
        int rowCount = 0, colCount = 0;
        public AdvancedCharts()
        {
            InitializeComponent();
            Name = "Advanced Chart Types";

            //Init Controls
            _dataAdapter = new SpreadDataBindingAdapter() { Spread = fpSpread1, SheetName = "Sheet1", DataAutoCellTypes = false };
            _cbChartGroup.DataSource = _chartTypes.Keys.ToList();

            _cbChartGroup.SelectedIndexChanged += _cbChartGroup_SelectedIndexChanged;
            _cbChartType.SelectedIndexChanged += _cbChartType_SelectedIndexChanged;
            _chbView.CheckedChanged += (s, e) => { fpSpread1_Sheet1.Charts[0].ViewType = _chbView.Checked ? ChartViewType.View3D : ChartViewType.View2D; };

            _cbChartGroup_SelectedIndexChanged(this, new EventArgs());
        }

        private void _cbChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var grpName = _cbChartGroup.SelectedItem.ToString();
            var typeName = _cbChartType.SelectedItem.ToString();
            var series = _chartTypes[grpName][typeName];

            fpSpread1_Sheet1.Charts.Clear();
            var cellRange = grpName == "Hierarchy"? new CellRange(1, 0, rowCount - 1, colCount) : new CellRange(0, 0, rowCount, colCount);
            var view = _chbView.Checked ? ChartViewType.View3D : ChartViewType.View2D;
            fpSpread1_Sheet1.AddChart(cellRange, series, 600, 500, 100, 150, view, true);

            SetChartProperties(grpName, typeName);
        }

        private void SetChartProperties(string grpName, string typeName)
        {
            var chartType = grpName != typeName ? string.Join(" ", typeName, grpName) : grpName;
            //Set Header
            fpSpread1_Sheet1.Charts[0].Model.LabelAreas.Clear();
            fpSpread1_Sheet1.Charts[0].Model.LabelAreas.Add(new LabelArea { Text = chartType, Location = new PointF(0.5f, 0.05f), AlignmentX = 0.5f, AlignmentY = 0.5f });

            var ser = fpSpread1_Sheet1.Charts[0].Model.PlotAreas[0].Series[0];
            if (chartType == "Waterfall")
                (ser as WaterfallSeries).SetTotal((ser as WaterfallSeries).Values.Count - 1, true);
        }

        private void _cbChartGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            string groupName = "Radar";
            if (_cbChartGroup.SelectedItem != null)
                groupName = _cbChartGroup.SelectedItem.ToString();

            //Set Data for selected chart group
            switch (groupName)
            {                
                case "Radar":
                    SetData(DataSource.GetMarketShareData(3));
                    break;
                case "Polar":
                    SetPolarData();
                    break;
                case "Frequency":
                    SetData(DataSource.GetStudentsScore());
                    break;
                case "Funnel":
                    SetData(DataSource.GetSalesStageData());
                    break;
                case "Waterfall":
                    SetData(DataSource.GetProfitData());
                    break;
                case "Box and Whisker":
                    SetData(DataSource.GetBoxWhiskerData());
                    break;
                case "Hierarchy":
                    SetData(DataSource.GetHierarchicalData());
                    break;
            }
            var chartTypes = _chartTypes.Where(x => x.Key == groupName).SelectMany(x => x.Value.Keys.ToList()).ToList();
            _cbChartType.DataSource = chartTypes;
        }
        private void SetPolarData()
        {
            ResetSheetData();
            fpSpread1_Sheet1.Cells[0, 0].Text = "Angles(°)";
            fpSpread1_Sheet1.Cells[1, 0].Text = "Sin(x)";
            fpSpread1_Sheet1.Cells[2, 0].Text = "Cos(x)";
            for(int i = 0; i <= 12; i++)
            {
                fpSpread1_Sheet1.Cells[0, i+1].Value = 30 * i;
                fpSpread1_Sheet1.Cells[1, i+1].Text = Math.Sin(30 * i * Math.PI / 180).ToString("0.00");
                fpSpread1_Sheet1.Cells[2, i+1].Text = Math.Cos(30 * i * Math.PI / 180).ToString("0.00");
            }
            rowCount = 3; colCount = 14;
        }

        private void SetData(List<object> list)
        {
            ResetSheetData();
            int r = 0, c = 1;
            foreach(var prop in list[0].GetType().GetProperties().Skip(1))
            {
                fpSpread1_Sheet1.Cells[r, c].Value = prop.Name;
                c++;
            }
            _dataAdapter.DataSource = list;
            _dataAdapter.MapperInfo = new MapperInfo(1, 0, list.Count, c);
            _dataAdapter.FillSpreadDataByDataSource();
            rowCount = list.Count + 1;
            colCount = c;
        }

        private void ResetSheetData()
        {
            _dataAdapter.DataSource = null;
            fpSpread1_Sheet1.ClearRange(0, 0, rowCount + 1, colCount+1, false, FarPoint.Win.Spread.ClipboardCopyOptions.All);
        }
    }
}


//
//AdvancedCharts.Designer.cs
//


namespace Spread.Charts
{
    partial class AdvancedCharts
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this._lChartGroup = new System.Windows.Forms.Label();
            this._cbChartGroup = new System.Windows.Forms.ComboBox();
            this._lChartType = new System.Windows.Forms.Label();
            this._cbChartType = new System.Windows.Forms.ComboBox();
            this._chbView = new System.Windows.Forms.CheckBox();
            this.fpSpread1 = new FarPoint.Win.Spread.FpSpread();
            this.fpSpread1_Sheet1 = new FarPoint.Win.Spread.SheetView();
            this.pnlMain.SuspendLayout();
            this.pnlControls.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread1_Sheet1)).BeginInit();
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.fpSpread1);
            // 
            // pnlControls
            // 
            this.pnlControls.Controls.Add(this._chbView);
            this.pnlControls.Controls.Add(this._cbChartType);
            this.pnlControls.Controls.Add(this._lChartType);
            this.pnlControls.Controls.Add(this._cbChartGroup);
            this.pnlControls.Controls.Add(this._lChartGroup);
            // 
            // _lChartGroup
            // 
            this._lChartGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this._lChartGroup.AutoSize = true;
            this._lChartGroup.Location = new System.Drawing.Point(6, 25);
            this._lChartGroup.Name = "_lChartGroup";
            this._lChartGroup.Size = new System.Drawing.Size(70, 13);
            this._lChartGroup.TabIndex = 0;
            this._lChartGroup.Text = "Chart Group :";
            // 
            // _cbChartGroup
            // 
            this._cbChartGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this._cbChartGroup.FormattingEnabled = true;
            this._cbChartGroup.Location = new System.Drawing.Point(20, 42);
            this._cbChartGroup.Name = "_cbChartGroup";
            this._cbChartGroup.Size = new System.Drawing.Size(111, 21);
            this._cbChartGroup.TabIndex = 1;
            // 
            // _lChartType
            // 
            this._lChartType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this._lChartType.AutoSize = true;
            this._lChartType.Location = new System.Drawing.Point(6, 81);
            this._lChartType.Name = "_lChartType";
            this._lChartType.Size = new System.Drawing.Size(65, 13);
            this._lChartType.TabIndex = 2;
            this._lChartType.Text = "Chart Type :";
            // 
            // _cbChartType
            // 
            this._cbChartType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this._cbChartType.FormattingEnabled = true;
            this._cbChartType.Location = new System.Drawing.Point(20, 97);
            this._cbChartType.Name = "_cbChartType";
            this._cbChartType.Size = new System.Drawing.Size(111, 21);
            this._cbChartType.TabIndex = 3;
            // 
            // _chbView
            // 
            this._chbView.AutoSize = true;
            this._chbView.Location = new System.Drawing.Point(9, 138);
            this._chbView.Name = "_chbView";
            this._chbView.Size = new System.Drawing.Size(66, 17);
            this._chbView.TabIndex = 4;
            this._chbView.Text = "3D View";
            this._chbView.UseVisualStyleBackColor = true;
            // 
            // fpSpread1
            // 
            this.fpSpread1.AccessibleDescription = "";
            this.fpSpread1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.fpSpread1.Location = new System.Drawing.Point(0, 0);
            this.fpSpread1.Name = "fpSpread1";
            this.fpSpread1.Sheets.AddRange(new FarPoint.Win.Spread.SheetView[] {
            this.fpSpread1_Sheet1});
            this.fpSpread1.Size = new System.Drawing.Size(477, 487);
            this.fpSpread1.TabIndex = 0;
            // 
            // fpSpread1_Sheet1
            // 
            this.fpSpread1_Sheet1.Reset();
            this.fpSpread1_Sheet1.SheetName = "Sheet1";
            // Formulas and custom names must be loaded with R1C1 reference style
            this.fpSpread1_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            this.fpSpread1_Sheet1.RowHeader.Columns.Default.Width = 35F;
            this.fpSpread1_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;
            // 
            // AdvancedCharts
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "AdvancedCharts";
            this.pnlMain.ResumeLayout(false);
            this.pnlControls.ResumeLayout(false);
            this.pnlControls.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread1_Sheet1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label _lChartGroup;
        private System.Windows.Forms.CheckBox _chbView;
        private System.Windows.Forms.ComboBox _cbChartType;
        private System.Windows.Forms.Label _lChartType;
        private System.Windows.Forms.ComboBox _cbChartGroup;
        private FarPoint.Win.Spread.FpSpread fpSpread1;
        private FarPoint.Win.Spread.SheetView fpSpread1_Sheet1;
    }
}


//
//DataService.cs
//

using Spread.Common.DataStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spread.Charts
{
    public class DataSource
    {
        static Random rnd = new Random();
        public static List<object> GetMarketShareData(int count)
        {
            var data = new List<object>();
            for(int i = 1; i <= count; i++)
                data.Add(new { Year = DateTime.Now.Year - i, North = rnd.Next(100, 500), East=rnd.Next(100,500), West = rnd.Next(100,500), South = rnd.Next(100,500), NorthEast=rnd.Next(100,500) });
            return data;
        }
        public static List<object> GetStockData()
        {
            var data = new List<object>();
            var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 2, 1);
            for(int i = 0; i < 5; i++)
            {
                data.Add(new
                {
                    Date = startDate.AddDays(i).ToShortDateString(),
                    Open = rnd.Next(40, 60),
                    High = rnd.Next(60, 70),
                    Low = rnd.Next(30, 40),                    
                    Close = rnd.Next(40, 60),                    
                });
            }
            return data;
        }
        public static List<object> GetStudentsScore()
        {
            var data = new List<object>();
            for(int i = 1; i <= 20; i++)
                data.Add(new {Name = "Class"+((i%4)+1), Score = rnd.Next(20,99)});
            return data;
        }
        public static List<object> GetPolarData()
        {
            var data = new List<object>();
            return data;
        }
        public static List<object> GetSalesStageData()
        {
            var data = new List<object>();
            data.Add(new { Stage = "Leads", Value = 100 });
            data.Add(new { Stage = "Emails Sent", Value = 70 });
            data.Add(new { Stage = "Replies", Value = 45 });
            data.Add(new { Stage = "Quotes", Value = 25 });
            data.Add(new { Stage = "Purchases", Value = 5 });
            return data;
        }
        public static List<object> GetProfitData()
        {
            var data = new List<object>();
            data.Add(new { Period = (DateTime.Now.Year-2).ToString(), Profit = rnd.Next(1000,5000) });
            data.Add(new { Period = "Jan", Profit = rnd.Next(100, 200) });
            data.Add(new { Period = "Feb", Profit = rnd.Next(100, 200) });
            data.Add(new { Period = "Mar", Profit = -rnd.Next(50, 100) });
            data.Add(new { Period = "Apr", Profit = -rnd.Next(50, 100) });
            data.Add(new { Period = "May", Profit = -rnd.Next(50, 100) });
            data.Add(new { Period = "Jun", Profit = rnd.Next(100, 150) });
            data.Add(new { Period = "Jul", Profit = rnd.Next(100, 150) });
            data.Add(new { Period = "Aug", Profit = rnd.Next(100, 150) });
            var total = data.Sum(x => (x as dynamic).Profit);
            data.Add(new { Period = "Total", Profit = total });
            return data;
        }
        public static List<object> GetBoxWhiskerData()
        {
            var data = new List<object>();
            var cheese = new string[] { "Asiago", "Gouda", "Havarti", "Swiss" };
            for(int i = 0; i <= 15; i++)
                data.Add(new { Cheese = cheese[i % cheese.Count()], Store1 = rnd.Next(5, 30), Store2 = rnd.Next(5, 30), Store3 = rnd.Next(5, 30) });
            return data;
        }

        public static List<object> GetHierarchicalData()
        {
            var data = new List<object>();
            data.Add(new { Continent = "America", Country = "US".ToString(), GDPPrice = 19362 });
            data.Add(new { Continent = "America", Country = "Brazil".ToString(), GDPPrice = 2081 });
            data.Add(new { Continent = "America", Country = "Canada".ToString(), GDPPrice = 1640 });
            data.Add(new { Continent = "Asia", Country = "China".ToString(), GDPPrice = 2439 });
            data.Add(new { Continent = "Asia", Country = "Japan".ToString(), GDPPrice = 4884 });
            data.Add(new { Continent = "Asia", Country = "India".ToString(), GDPPrice = 2439 });
            data.Add(new { Continent = "Europe", Country = "Germany".ToString(), GDPPrice = 3652 });
            data.Add(new { Continent = "Europe", Country = "France".ToString(), GDPPrice = 2575 });
            data.Add(new { Continent = "Europe", Country = "Italy".ToString(), GDPPrice = 1921 });
            data.Add(new { Continent = "Europe", Country = "UK".ToString(), GDPPrice = 2565 });
            return data;
        }
    }
}

